package gfo

/*Stage
* -----------------------------
* The Stage is where the battle takes place in the game world; there are dozens of them in the game,
* but only a handful are tournament legal.*/
class Stage {
    String name
    String description//causing errors, not sure why
    String imgFile
    static hasMany = [matches: Match]

    static constraints = {
        matches(nullable: true)
        description(nullable: true,
                    maxSize: 500)
        imgFile(nullable: true)
    }

    String toString(){
        "$name"
    }

    /*mostPlayedBy
    * ----------------------------------------
    * Examines all the matches that have been played on this Stage and returns the Player that has
    * played on it most. Used in Stage:show.gsp*/
    Player mostPlayedBy(){
        def players = [:]
        for (player in Player.list()){
            players[player] = 0
        }
        for (match in Match.list()){
            if (match.stage.id == this.id){
                for (ms in match.players){
                    players[ms.player] ++
                }
            }
        }
        def keys = players.keySet().toList()
        def vals = players.values().toList()
        if (vals.max()==0){
            return null
        }
        return keys[vals.indexOf(vals.max())]
    }

    /*mostWonBy
    * ----------------------------------------
    * Examines all the matches that have been played on this stage and returns the Player that has
    * won on it the most. Used in Stage:show.gsp*/
    Player mostWonBy(){
        def players = [:]
        for (player in Player.list()){
            players[player] = 0
        }
        for (match in Match.list()){
            if (match.stage.id == this.id){
                for (ms in match.players){
                    if (ms.winner){
                        players[ms.player] ++
                    }
                }
            }
        }
        def keys = players.keySet().toList()
        def vals = players.values().toList()
        if (vals.max()==0){
            return null
        }
        return keys[vals.indexOf(vals.max())]
    }
}
